package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.opencsv.CSVReader;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IAHousingService;
import com.ruoyi.system.util.LoginUtils;
import com.sun.org.apache.xerces.internal.xs.StringList;
import org.apache.commons.io.CopyUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.DataBinder;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.rmi.AccessException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 房屋信息Service业务层处理
 *
 * @author gf
 * @date 2024-11-23
 */
@Service
@Transactional
public class AHousingServiceImpl implements IAHousingService {
    @Autowired
    private AHousingMapper aHousingMapper;

    @Autowired
    private ADictNatureUserMapper aDictNatureUserMapper;

    @Autowired
    private ADictAdvantageUserMapper aDictAdvantageUserMapper;

    @Autowired
    private ADictAreaMapper aDictAreaMapper;

    @Autowired
    private ADictBudgetMapper aDictBudgetMapper;

    @Autowired
    private AHousingFollowMapper aHousingFollowMapper;

    @Autowired
    private IwebshopAreasMapper iwebshopAreasMapper;

    @Autowired
    private ARollMapper aRollMapper;

    @Autowired
    private ConfigureGlobalMapper configureGlobalMapper;
    /**
     * 查询房屋信息
     *
     * @param id 房屋信息主键
     * @return 房屋信息
     */
    @Override
    public AHousingHgVO selectAHousingById(Long id) {
        AHousingHgVO vo  =  new AHousingHgVO();
        AHousing aHousing = aHousingMapper.selectAHousingById(id);
        BeanUtils.copyProperties(aHousing,vo);

        List<ADictAdvantageUser> adList = aDictAdvantageUserMapper.selectADictAdvantageUserByUserIdAndHouId(aHousing.getUserId(),id);
        List<Long> adLong = adList.stream().map(ADictAdvantageUser::getAdvId).collect(Collectors.toList());
        vo.setAdList(adLong);

        List<ADictNatureUser> naList = aDictNatureUserMapper.selectADictNatureUserByUserId(aHousing.getUserId());
        List<Long> naLong = naList.stream().map(ADictNatureUser::getNaId).collect(Collectors.toList());
        vo.setNaList(naLong);

        List<String> li = new ArrayList<>(3);
        li.add(aHousing.getProvinceId());
        li.add(aHousing.getCityId());
        li.add(aHousing.getRegion());
        vo.setRegionList(li);

        return vo;
    }

    /**
     * 查询房屋信息列表
     *
     * @param aHousing 房屋信息
     * @return 房屋信息
     */
    @Override
    public List<AHousing> selectAHousingList(AHousing aHousing) {
        return aHousingMapper.selectAHousingList(aHousing);
    }

    /**
     * 新增房屋信息
     *
     * @param aHousing 房屋信息
     * @return 结果
     */
    @Override
    public int insertAHousing(AHousing aHousing) {
        aHousing.setCreateTime(DateUtils.getNowDate());
        aHousing.setUpdateTime(DateUtils.getNowDate());
        aHousing.setDataTime(DateUtils.getNowDate());
        if(aHousing.getPicture() == null || aHousing.getPicture() == ""){
            ConfigureGlobal gl = configureGlobalMapper.selectConfigureGlobalById(1L);
            aHousing.setPicture(gl.getDefaultImg());
        }
        aHousingMapper.insertAHousing(aHousing);

        if(StringUtils.isNotEmpty(aHousing.getAdvanageId())){
            ADictAdvantageUser ad = new ADictAdvantageUser();
            ad.setUserId(aHousing.getUserId());
            ad.setHoId(aHousing.getId());
            List<ADictAdvantageUser> adList = aDictAdvantageUserMapper.selectADictAdvantageUserList(ad);
            if(adList.size() == 0){
                addAdvamtageUser(aHousing);
            }else{
                aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
                addAdvamtageUser(aHousing);
            }
        }else{
            aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
        }

        return 1;
    }


    private void addAdvamtageUser(AHousing aHousing) {
        String[] str = aHousing.getAdvanageId().split(",");
        for (String st :str){
            ADictAdvantageUser advantage = new ADictAdvantageUser();
            advantage.setUserId(aHousing.getUserId());
            advantage.setCreateTime(DateUtils.getNowDate());
            advantage.setAdvId(Long.valueOf(st));
            advantage.setHoId(aHousing.getId());
            aDictAdvantageUserMapper.insertADictAdvantageUser(advantage);
        }
    }


    /**
     * 修改房屋信息
     *
     * @param aHousing 房屋信息
     * @return 结果
     */
    @Override
    public int updateAHousing(AHousing aHousing) {
        if(StringUtils.isNotEmpty(aHousing.getAdvanageId())){
            ADictAdvantageUser ad = new ADictAdvantageUser();
            ad.setUserId(aHousing.getUserId());
            ad.setHoId(aHousing.getId());
            List<ADictAdvantageUser> adList = aDictAdvantageUserMapper.selectADictAdvantageUserList(ad);
            if(adList.size() == 0){
                addAdvamtageUser(aHousing);
            }else{
                aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
                addAdvamtageUser(aHousing);
            }
        }else{
            aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
        }
        aHousing.setUpdateTime(DateUtils.getNowDate());
        aHousing.setDataTime(DateUtils.getNowDate());
        if(aHousing.getIsPay().equals("2")){
            aHousing.setPayTime(DateUtils.getNowDate());
        }
        return aHousingMapper.updateAHousing(aHousing);
    }

    /**
     * 批量删除房屋信息
     *
     * @param ids 需要删除的房屋信息主键
     * @return 结果
     */
    @Override
    public int deleteAHousingByIds(Long[] ids) {
        for (int i = 0 ; i<ids.length;i++){
            aHousingFollowMapper.deleteAHousingFollowByHousId(ids[i]);
        }
        return aHousingMapper.deleteAHousingByIds(ids);
    }

    /**
     * 删除房屋信息信息
     *
     * @param id 房屋信息主键
     * @return 结果
     */
    @Override
    public int deleteAHousingById(Long id) {
        return aHousingMapper.deleteAHousingById(id);
    }

    /**
     * 批量逻辑删除房屋信息
     *
     * @param ids 需要删除的房屋信息主键
     * @return 结果
     */
    @Override
    public int logicDeleteAHousingByIds(Long[] ids) {
        return aHousingMapper.logicDeleteAHousingByIds(ids);
    }
    /**
     * 逻辑删除房屋信息信息
     *
     * @param id 房屋信息主键
     * @return 结果
     */
    @Override
    public int logicDeleteAHousingById(Long id) {
        return aHousingMapper.logicDeleteAHousingById(id);
    }

    @Override
    public List<AHousingBackXcxVO> selectAHousingXcxList(AHousingXcxVO aHousing) {
        if(aHousing.getAreId() != null && !aHousing.getAreId().equals("1")){//1是不限
            ADictArea aDictArea = aDictAreaMapper.selectADictAreaById(aHousing.getAreId());
            aHousing.setMinArea(aDictArea.getMinBudget());
            aHousing.setMaxArea(aDictArea.getMaxBudget());
        }
        if(aHousing.getRentId() != null && !aHousing.getRentId().equals("1") ){//1是不限
            ADictBudget aDictBudget = aDictBudgetMapper.selectADictBudgetById(aHousing.getRentId());
            aHousing.setMinRent(aDictBudget.getMinBudget());
            aHousing.setMaxRent(aDictBudget.getMaxBudget());
        }
        ConfigureGlobal gl = configureGlobalMapper.selectConfigureGlobalById(1L);
        PageUtils.startPage();
        List<AHousingBackXcxVO> list = aHousingMapper.selectAHousingXcxList(aHousing);
        if(gl.getIsRoll()){
            for (int i = 0; i<list.size();i++){
                List<ARollVO> vo = aRollMapper.selectARollByVoList(Integer.valueOf(gl.getHousRoll()));
                list.get(i).setARollVo(vo);
            }
        }
        return list;
    }


    @Override
    public AHousingInfoXcxVO selectAHousingByXcxId(Long id) {
        AHousingInfoXcxVO vo = aHousingMapper.selectAHousingByXcxId(id);
        ConfigureGlobal gl = configureGlobalMapper.selectConfigureGlobalById(1L);
        if(gl.getIsRoll()){
            List<ARollVO> roll = aRollMapper.selectARollByVoList(Integer.valueOf(gl.getHousRoll()));
            vo.setARollVo(roll);
        }
        return vo;
    }

    @Override
    public int insertAHousingXcx(AHousing aHousing) {
        aHousing.setCreateTime(DateUtils.getNowDate());
        aHousing.setUpdateTime(DateUtils.getNowDate());
        aHousing.setUserId(LoginUtils.getUser().getId());
        aHousing.setDataTime(DateUtils.getNowDate());
        if(aHousing.getPicture() == null || aHousing.getPicture() == ""){
            ConfigureGlobal gl = configureGlobalMapper.selectConfigureGlobalById(1L);
            aHousing.setPicture(gl.getDefaultImg());
        }
        aHousingMapper.insertAHousing(aHousing);

        System.out.println(aHousing.getAdvanageId());
        if(StringUtils.isNotEmpty(aHousing.getAdvanageId())){
            ADictAdvantageUser ad = new ADictAdvantageUser();
            ad.setUserId(aHousing.getUserId());
            ad.setHoId(aHousing.getId());
            List<ADictAdvantageUser> adList = aDictAdvantageUserMapper.selectADictAdvantageUserList(ad);
            if(adList.size() == 0){
                addAdvamtageUser(aHousing);
            }else{
                aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
                addAdvamtageUser(aHousing);
            }
        }else{
            aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
        }
        return Math.toIntExact(aHousing.getId());
    }

    @Override
    public int insertAHousingXcxEdit(AHousing aHousing) {
        if(StringUtils.isNotEmpty(aHousing.getAdvanageId())){
            ADictAdvantageUser ad = new ADictAdvantageUser();
            ad.setUserId(aHousing.getUserId());
            ad.setHoId(aHousing.getId());
            List<ADictAdvantageUser> adList = aDictAdvantageUserMapper.selectADictAdvantageUserList(ad);
            if(adList.size() == 0){
                addAdvamtageUser(aHousing);
            }else{
                aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
                addAdvamtageUser(aHousing);
            }
        }else{
            aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
        }
        aHousing.setDataTime(DateUtils.getNowDate());
        aHousing.setUpdateTime(DateUtils.getNowDate());
        return aHousingMapper.updateAHousing(aHousing);
    }

    @Override
    public SumNumVO selectAHousingCountHousing() {
        Long userId = LoginUtils.getUser().getId();
        return aHousingMapper.selectAHousingCountHousing(userId);
    }

    @Override
    public SumNumVO selectAHousingCountRegion(String region) {
        return aHousingMapper.selectAHousingCountRegion(region);
    }

    @Override
    public List<AHousingBackXcxVO> selectAHousingMyRegion(AHousing aHousing) {
        return aHousingMapper.selectAHousingMyRegion(aHousing);
    }

    @Override
    public List<AHousingBackXcxVO> selectAHousingMyHousing(PageVO vo) {
        Long userId = LoginUtils.getUser().getId();
        vo.setUserId(userId);
        PageUtils.startPage();
        return aHousingMapper.selectAHousingMyHousing(vo);
    }


    @Override
    public AHousingInfoGetXcxVO selectAHousingByGetXcxId(Long id) {
        return aHousingMapper.selectAHousingByGetXcxId(id);
    }

    @Override
    public int selectAHousingByUpdateVisit(Long id) {
        return aHousingMapper.selectAHousingByUpdateVisit(id);
    }

    @Override
    public int selectAHousingByUpdateExposure(Long id) {
        return aHousingMapper.selectAHousingByUpdateExposure(id);
    }

    @Override
    public int selectAHousingByUpdatePhone(Long id) {
        return aHousingMapper.selectAHousingByUpdatePhone(id);
    }

    @Override
    public Long insertAHousingXcxHAdd(AHousing aHousing) {
        aHousing.setUserId(LoginUtils.getUser().getId());
        aHousing.setCreateTime(DateUtils.getNowDate());
        aHousing.setDataTime(DateUtils.getNowDate());
        if(aHousing.getPicture() == null || aHousing.getPicture() == ""){
            ConfigureGlobal gl = configureGlobalMapper.selectConfigureGlobalById(1L);
            aHousing.setPicture(gl.getDefaultImg());
        }
        aHousingMapper.insertAHousing(aHousing);
        if(StringUtils.isNotEmpty(aHousing.getAdvanageId())){
            ADictAdvantageUser ad = new ADictAdvantageUser();
            ad.setUserId(aHousing.getUserId());
            ad.setHoId(aHousing.getId());
            List<ADictAdvantageUser> adList = aDictAdvantageUserMapper.selectADictAdvantageUserList(ad);
            if(adList.size() == 0){
                addAdvamtageUser(aHousing);
            }else{
                aDictAdvantageUserMapper.deleteADictAdvantageUserByUserId(aHousing.getUserId());
                addAdvamtageUser(aHousing);
            }
        }
        return aHousing.getId();
    }

    @Override
    public int deleteAHousingByXcxId(Long id) {
        AHousingFollow fo = new AHousingFollow();
        fo.setUserId(LoginUtils.getUser().getId());
        fo.setHousId(id);
        List<AHousingFollow> foS = aHousingFollowMapper.selectAHousingFollowList(fo);
        if(foS.size() > 0){
            for (int o = 0 ; o<foS.size();o++){
                aHousingFollowMapper.deleteAHousingFollowById(foS.get(o).getId());
            }
        }
        return aHousingMapper.deleteAHousingById(id);
    }

    @Override
    public int updateAHousingUpdaTime(Long id) {
        AHousing housing = aHousingMapper.selectAHousingById(id);
        housing.setDataTime(DateUtils.getNowDate());
        return aHousingMapper.updateAHousing(housing);
    }

    @Override
    public int updateAHousingUploadFile(MultipartFile file,Long userId) throws Exception {
        InputStreamReader inReader = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
        CSVReader reader = new CSVReader(inReader);
        // 读取CSV文件的所有行
        List<String[]> lines = reader.readAll();
        lines.remove(0);
        for (String[] line : lines) {
            if(!line[0].isEmpty()){
                AHousing ho = new AHousing();
                for (int i = 0; i<line.length;i++){
                    if(StringUtils.isNotEmpty(line[i])){
                        if(i == 0){
                            ho.setIsType(Long.valueOf(line[i]));
                        }
                        if(i == 1) {
                            ho.setName(line[i].trim());
                        }
                        if(i == 2) {
                            ho.setPhone(line[i].trim());
                        }
                        if(i == 3) {
                            if (line[i].contains("/")) {
                                String[] arr = line[i].split("/");
                                for (int t = 0; t < arr.length; t++) {
                                    List<IwebshopAreasVO> vo = iwebshopAreasMapper.selectIwebshopAreasByAreaName(arr[t].trim());
                                    if(t == 0){
                                        if(vo.size() > 0){
                                            ho.setProvinceId(vo.get(0).getId());
                                        }else{
                                            throw new ServiceException("省--查询为空！请核对--"+line[i]+"这个数据的准确性！");
                                        }
                                    }
                                    if(t == 1) {
                                        if(vo.size() > 0){
                                            ho.setCityId(vo.get(0).getId());
                                        }else{
                                            throw new ServiceException("市--查询为空！请核对--"+line[i]+"这个数据的准确性！");
                                        }
                                    }
                                    if(t == 2){
                                        if(vo.size() > 0){
                                            ho.setRegion(vo.get(0).getId());
                                        }else{
                                            throw new ServiceException("区--询为空！请核对--"+line[i]+"这个数据的准确性！");
                                        }
                                    }
                                }
                            }
                            ho.setRegionAllName(line[i]);
                        }
                        if(i == 4) {
    //                        ho.setPicture("https://laizhuanpu-1259519650.cos.ap-guangzhou.myqcloud.com/2024/12/30/1735551671113-cd35f764870adcfbf6267ae64867fd4.png");
                            ho.setPicture(line[i].trim());
                        }
                        if(i == 5) {
                            ho.setNatureId(1L);
                        }
                        if(i == 6) {
                            ho.setAdvanageId("1");
                        }
                        if(i == 7) {
                            ho.setIsQuick(line[i].trim());
                        }

                        if(i == 8) {
                            ho.setAreaNum(line[i].trim());
                        }
                        if(i == 9) {
                            ho.setRent(line[i].trim());
                        }
                        if(i == 10) {
                            ho.setTransferFee(line[i].trim());
                        }
                        if(i == 11) {
                            ho.setAreaDetails(line[i].trim());
                        }
                    }else{
                        new ServiceException("不能为空！");
                    }
                }
                ho.setIsUpload("1");
                ho.setUserId(userId);
                aHousingMapper.insertAHousing(ho);
            }else{
                continue;
            }
        }
        return 0;
    }

    @Override
    public List<AHousingGoodXcxVO> selectAHousingXcxGoddList(AHousing aHousing) {
        return aHousingMapper.selectAHousingXcxGoddList(aHousing);
    }

    @Override
    public int selectAHousingBySendInfor(Long id){
        AHousing housing = aHousingMapper.selectAHousingById(id);
//        String url = "https://ppz.gfxxjs.com/wx/#/pages/index/detailsPayVip?id="+housing.getId();
        AliSmsUtils.sendInfor(housing.getPhone(),String.valueOf(id));
        return 1;
    }

}
